// @flow
import React, { Component } from 'react'
import styles from './HistoryPolar.css'
import { Spin, Row, Col, Button, Radio, message, Popover } from 'antd'
import R from 'ramda'
import moment from 'moment'
import echarts from 'echarts/lib/echarts'
import Highcharts from 'highcharts-release'
import 'echarts/lib/component/title'
import 'echarts/lib/component/tooltip'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
const RadioGroup = Radio.Group
type Props = {
  title: string,
  closeModal: Function,
  checkTime: number,
  checkName: string,
  deviceData: Object,
  historyCond: Object,
  channel_id: number,
  requestType: string // 如果值是wx就是小程序访问的，接口变成域名
}

type States = {
  visible: boolean,
  loading: boolean,
  requestData: Object,
  PolarData: Array<Object>,
  channelData: Array<Object>,
  channelIds: Array<string>,
  Indictor: Array<Object>,
  infoData: Array<Object>,
  minPolar: number,
  maxPolar: number,
  plainOptions: Array<Object>,
  channelValue: string,
  samples: string, // 采样点数
  rotatDirec: string, // 旋转角度
  orientDegree: string, // 安装角度
  activity: string, // 速度计算方式（有键无健）
  samplesFinal: string, // 展示用到的采样点数
  rotatDirecFinal: string, // 展示用到的旋转角度
  orientDegreeFinal: string, // 展示用到的安装角度
  activityFinal: string, // 展示用到的速度计算方式
  bearingName: string,
  bearingNameFinal: string // 展示用到的轴承名称
}
class HistoryPolar extends Component {
  props: Props
  state: States
  myChart: any
  closeModal: Function
  draw: Function
  getDynamicData: Function
  getOrgTrack: Function
  getChannel: Function
  channelChange: Function
  refer: Function
  getIndictor: Function
  kmxDraw: Function
  lineDraw: Function
  constructor (props: Object) {
    super(props)
    this.state = {
      visible: true,
      loading: false,
      requestData: {},
      PolarData: [],
      channelData: [],
      channelIds: [],
      Indictor: [],
      infoData: [],
      minPolar: -10,
      maxPolar: 10,
      plainOptions: [],
      channelValue: '',
      samples: '',
      rotatDirec: '',
      orientDegree: '',
      activity: '',
      samplesFinal: '',
      rotatDirecFinal: '',
      orientDegreeFinal: '',
      activityFinal: '',
      bearingName: '',
      bearingNameFinal: ''
    }
    this.closeModal = this.closeModal.bind(this)
    this.getDynamicData = this.getDynamicData.bind(this)
    this.draw = this.draw.bind(this)
    this.getOrgTrack = this.getOrgTrack.bind(this)
    this.getChannel = this.getChannel.bind(this)
    this.channelChange = this.channelChange.bind(this)
    this.refer = this.refer.bind(this)
    this.getIndictor = this.getIndictor.bind(this)
    this.kmxDraw = this.kmxDraw.bind(this)
    this.lineDraw = this.lineDraw.bind(this)
  }

  componentWillMount () {
    this.getIndictor() // 取所有的指标
    this.getChannel()
  }

  componentWillReceiveProps (nextProps: Props) {
    if (!R.equals(nextProps, this.props)) {
      this.getChannel() // 重新确认默认值并重新画图
      // this.getDynamicData(nextProps)
    }
  }

  componentDidMount () {
    this.draw()
    // this.refer()
  }

  getIndictor () {
    const { deviceData, historyCond, requestType } = this.props
    const sensorType = historyCond.monitors[0].sensorType
    const id = deviceData.id
    let url = `${__SERVICE_API__}device/devices/${id}/monitors?group`
    if (requestType === 'wx') {
      url = `${__WXSERVICE_API__}device/devices/${id}/monitors?group`
    }
    universalFetch(url)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        const Indictor = json.result[sensorType][sensorType]
        this.setState({
          Indictor: Indictor
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  getChannel () {
    // 通道
    const { deviceData, historyCond, requestType } = this.props
    const sensorType = historyCond.monitors[0].sensorType
    const id = deviceData.id
    let url = `${__SERVICE_API__}device/devices/${id}/channel-ids`
    if (requestType === 'wx') {
      url = `${__WXSERVICE_API__}device/devices/${id}/channel-ids`
    }
    universalFetch(url)
      .then((res) => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        // const results = [
        //   {
        //     sensorType: '',
        //     channelIds: [{
        //       id: 0,
        //       name: '名称1',
        //       bearingName: '轴承1'
        //     },
        //     {
        //       id: 1,
        //       name: '名称2',
        //       bearingName: '轴承1'
        //     },
        //     {
        //       id: 2,
        //       name: '名称3',
        //       bearingName: '轴承2'
        //     },
        //     {
        //       id: 3,
        //       name: '名称4',
        //       bearingName: '轴承2'
        //     }]
        //   }
        // ]
        const component = this
        const channelData = json.result.filter((dd) => dd.sensorType === sensorType)
        const { channel_id } = this.props
        this.setState({
          channelData: channelData
          // channelData: results
        }, () => {
          // 对数据处理，
          let defaultBearingName = '' // 默认的通道对应的bearingName
          // let plainOptions = []
          // if (channelData.length > 0) {
          //   plainOptions = channelData[0].channelIds.map((d) => {
          //     return { label: d.name, value: d.id }
          //   })
          // }
          // 把channelData以相同的bearingName重新组合
          var hash = {}
          var i = 0
          var res = []
          var defaultsamples // 默认的samples值
          var defaultrotatDirec // 默认的rotatDirec值
          var defaultorientDegree // 默认的orientDegree值
          var defaultactivity
          if (channelData.length > 0) {
            channelData[0].channelIds.forEach(function (item) {
              // 找到默认通道对应的bearingName
              if (Number(item.id) === Number(channel_id)) {
                defaultBearingName = item.bearingName
                // 找到默认channel_id对应的samples值
                defaultsamples = item.samples
                defaultrotatDirec = item.rotatDirec
                defaultorientDegree = item.orientDegree
                defaultactivity = item.activity
              }
              // 组合
              var bearingName = item.bearingName
              if (bearingName) {
                hash[bearingName]
                ? res[hash[bearingName] - 1].channels.push({ id:item.id, name: item.name })
                : hash[bearingName] = ++i && res.push({
                  channels: [{ id:item.id, name: item.name }],
                  bearingName: bearingName
                })
              }
            })
          }
          // plainOptions是合成后的结果，【{label:"bearing_name_1"value:"0_1"}】
          let plainOptions = []
          let channelValue = ''
          let channelIds
          plainOptions = res.map((d) => {
            const ids = d.channels.map((data) => {
              return data.id
            })
            // 找到默认的通道值
            if (d.bearingName === defaultBearingName) {
              channelValue = ids.join('_')
              channelIds = ids
            }
            return { label: d.bearingName, value: ids.join('_') }
          })
          component.setState({
            bearingName: defaultBearingName,
            plainOptions: plainOptions,
            channelValue: channelValue,
            channelIds: channelIds,
            samples: defaultsamples,
            rotatDirec: defaultrotatDirec,
            orientDegree: defaultorientDegree,
            activity: defaultactivity
          }, () => {
            this.getDynamicData(this.props)
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  channelChange (values: Object) {
    const channelIds = values.target.value.split('_')
    const { channelData } = this.state
    let samples // 查找采样点
    let rotatDirec // 旋转角度
    let orientDegree // 安装角度
    let activity // 速度计算方式
    if (channelData.length > 0) {
      const sample = channelData[0].channelIds.filter((dd) => Number(dd.id) === Number(channelIds[0]))
      samples = sample[0].samples
      rotatDirec = sample[0].rotatDirec
      orientDegree = sample[0].orientDegree
      activity = sample[0].activity
    }
    this.setState({
      bearingName: values.target.title,
      samples: samples,
      rotatDirec: rotatDirec,
      orientDegree: orientDegree,
      activity: activity,
      channelIds: channelIds,
      channelValue: values.target.value
    })
  }

  refer () {
    // const { channelIds } = this.state
    // if (channelIds.length !== 2) {
    //   message.info('请选择测点')
    //   return
    // }
    this.getDynamicData(this.props)
  }
  kmxDraw () {
    const { channelIds, samples, rotatDirec, orientDegree, activity, bearingName } = this.state
    if (channelIds.length !== 2) {
      message.info('请选择测点')
      return
    }
    // 从Kmx中直接取出轴心轨迹结果
    this.setState({
      loading: true
    })
    const { Indictor } = this.state
    let inds = ['dyna_value']
    // let indsName = ['动态数据']
    Indictor.map((d) => {
      inds.push(d.kmxVariableNameEn)
      // indsName.push(d.variableName)
    })
    let indsName = ['动态值', '转速', '通频值']
    const { deviceData, historyCond, checkTime, requestType } = this.props
    const fieldGroup = historyCond.monitors
    const deviceNo = deviceData.deviceNo.split('_')
    const postBody = JSON.stringify({
      fieldGroup: fieldGroup[0].En,
      fields: ['dyna_value', 'speed', 'direc'],
      // fields: inds,
      timeRange: {
        start: checkTime,
        end: checkTime + 1
      },
      coValueFilter: {
        idFieldFilter: {
          factory_id: { '$eq': String(deviceNo[0]) },
          equipment_id: { '$eq': String(deviceNo[1]) },
          machine_id: { '$eq': String(deviceNo[2]) },
          datatype: { '$eq': '1' },
          '$or': channelIds.map((d, i) => {
            return { 'channel_id': { '$eq': String(d) } }
          })
        }
      }
    })

    let url = `${__KMX_REAL_TIME_API__}data-rows`
    if (requestType === 'wx') {
      url = `${__WXKMX_REAL_TIME_API__}data-rows`
    }
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: postBody
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 0) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      const results = json.results
      if (results && results.length > 0) {
        // 如果dyna_value没有value值就直接返回空数据
        if (!results[0].rows[0].values[0]) {
          this.setState({
            loading: false,
            bearingNameFinal: bearingName,
            samplesFinal: samples,
            rotatDirecFinal: rotatDirec,
            orientDegreeFinal: orientDegree,
            activityFinal: activity,
            PolarData: []
          }, () => {
            this.draw()
          })
          return
        }
        const n1 = results[0].rows[0].values[0].split(',')
        const n2 = results[1].rows[0].values[0].split(',')
        const speed = results[0].rows[0].values[1] // 注意speed在fields里的位置
        let infoData = [{ key: 'speed显示', name: '转速', value: speed }]
        for (var i = 0; i < indsName.length * 2; i++) {
          const l = i % indsName.length
          if (i < indsName.length) {
            infoData.push({ key: results[0].fields[l], name: 'X' + indsName[l], value: results[0].rows[0].values[l] })
          } else {
            infoData.push({ key: results[1].fields[l], name: 'Y' + indsName[l], value: results[1].rows[0].values[l] })
          }
        }
        let max = Math.max(...n1)
        if (max < Math.max(...n2)) {
          max = Math.max(...n2)
        }
        let min = Math.min(...n1)
        if (min > Math.min(...n2)) {
          min = Math.min(...n2)
        }
        this.setState({
          loading: false,
          bearingNameFinal: bearingName,
          samplesFinal: samples,
          rotatDirecFinal: rotatDirec,
          orientDegreeFinal: orientDegree,
          activityFinal: activity,
          minPolar: Math.floor(min),
          maxPolar: Math.ceil(max),
          PolarData: n1.map((d, i) => {
            return [d, n2[i]]
          }),
          infoData: infoData.filter((dd) => dd.key !== 'dyna_value' && dd.key !== 'speed')
        }, () => {
          this.draw()
        })
        // 画线图
        const spectrumCharts = [
          {
            chart: this.refs.linex,
            title: 'x轴',
            xtext: '',
            ytext: '',
            series: [
              {
                name: '',
                type: 'line',
                data: n1.map((d, i) => {
                  return [i, Number(d)]
                })
              }
            ]
          },
          {
            chart: this.refs.liney,
            title: 'y轴',
            xtext: '',
            ytext: '',
            series: [
              {
                name: '',
                type: 'line',
                data: n2.map((d, i) => {
                  return [i, Number(d)]
                })
              }
            ]
          }
        ]
        this.lineDraw(spectrumCharts)
      } else {
        // message.info('暂无数据')
        this.setState({
          loading: false,
          bearingNameFinal: bearingName,
          samplesFinal: samples,
          rotatDirecFinal: rotatDirec,
          orientDegreeFinal: orientDegree,
          activityFinal: activity,
          PolarData: []
        }, () => {
          this.draw()
        })
      }
    })
    .catch((error) => {
      console.error(error)
      this.setState({
        loading: false,
        bearingNameFinal: bearingName,
        samplesFinal: samples,
        rotatDirecFinal: rotatDirec,
        orientDegreeFinal: orientDegree,
        activityFinal: activity,
        PolarData: []
      }, () => {
        this.draw()
      })
    })
  }

  getDynamicData (props: Props) { // 原始轴心轨迹图
    this.setState({
      loading: true
    })
    const { Indictor } = this.state
    let inds = ['dyna_value']
    // let indsName = ['动态数据']
    Indictor.map((d) => {
      inds.push(d.kmxVariableNameEn)
      // indsName.push(d.variableName)
    })
    let indsName = ['动态值', '转速', '通频值']
    const { deviceData, historyCond, checkTime, requestType } = props
    const { channelIds, samples, rotatDirec, orientDegree, activity, bearingName } = this.state
    const fieldGroup = historyCond.monitors
    const deviceNo = deviceData.deviceNo.split('_')
    const postBody = JSON.stringify({
      fieldGroup: fieldGroup[0].En,
      fields: ['dyna_value', 'speed', 'direc'],
      // fields: inds,
      timeRange: {
        start: checkTime,
        end: checkTime + 1
      },
      coValueFilter: {
        idFieldFilter: {
          factory_id: { '$eq': String(deviceNo[0]) },
          equipment_id: { '$eq': String(deviceNo[1]) },
          machine_id: { '$eq': String(deviceNo[2]) },
          datatype: { '$eq': '1' },
          '$or': channelIds.map((d, i) => {
            return { 'channel_id': { '$eq': String(d) } }
          })
        }
      }
    })
    // const postBody = {
    //   'tsTable' : fieldGroup[0].En,
    //   // 'allCol' : 'true',
    //   'startTime' : checkTime,
    //   // 'endTime' : checkTime + 1,
    //   'queryConditions' : [
    //     {
    //       'colName' : 'factory_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[0])
    //     },
    //     {
    //       'colName' : 'equipment_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[1])
    //     },
    //     {
    //       'colName' : 'machine_id',
    //       'condition' : 'eq',
    //       'value' : String(deviceNo[2])
    //     },
    //     {
    //       'colName' : 'datatype',
    //       'condition' : 'eq',
    //       'value' : 1
    //     },
    //     {
    //       'colName' : 'channel_id',
    //       'condition' : 'in',
    //       'value' : channelIds
    //     }
    //   ],
    //   cols : ['dyna_value', 'speed', 'direc']
    // }
    // const token = localStorage.getItem('asset_token')
    let url = `${__KMX_REAL_TIME_API__}data-rows`
    if (requestType === 'wx') {
      url = `${__WXKMX_REAL_TIME_API__}data-rows`
    }
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
        // 'X-Auth': token
      },
      body: postBody
    })
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 0) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      const results = json.results
      if (results && results.length > 0) {
        // 如果dyna_value没有value值就直接返回空数据
        if (!results[0].rows[0].values[0]) {
          this.setState({
            loading: false,
            bearingNameFinal: bearingName,
            samplesFinal: samples,
            rotatDirecFinal: rotatDirec,
            orientDegreeFinal: orientDegree,
            activityFinal: activity,
            requestData:{}
          }, () => {
            this.getOrgTrack()
          })
          return
        }
        const n1 = results[0].rows[0].values[0].split(',')
        const n2 = results[1].rows[0].values[0].split(',')
        const speed = results[0].rows[0].values[1] // 注意speed在fields里的位置
        let infoData = [{ key: 'speed显示', name: '转速', value: speed }]
        for (var i = 0; i < indsName.length * 2; i++) {
          const l = i % indsName.length
          if (i < indsName.length) {
            infoData.push({ key: results[0].fields[l], name: 'X' + indsName[l], value: results[0].rows[0].values[l] })
          } else {
            infoData.push({ key: results[1].fields[l], name: 'Y' + indsName[l], value: results[1].rows[0].values[l] })
          }
        }
        this.setState({
          bearingNameFinal: bearingName,
          samplesFinal: samples,
          rotatDirecFinal: rotatDirec,
          orientDegreeFinal: orientDegree,
          activityFinal: activity,
          requestData: { 'n1':n1, 'n2': n2 },
          infoData: infoData.filter((dd) => dd.key !== 'dyna_value' && dd.key !== 'speed')
        }, () => {
          this.getOrgTrack()
        })
      } else {
        // message.info('暂无数据')
        this.setState({
          loading: false,
          bearingNameFinal: bearingName,
          samplesFinal: samples,
          rotatDirecFinal: rotatDirec,
          orientDegreeFinal: orientDegree,
          activityFinal: activity,
          requestData:{}
        }, () => {
          this.getOrgTrack()
        })
      }
    })
    .catch((error) => {
      console.error(error)
      this.setState({
        loading: false,
        bearingNameFinal: bearingName,
        samplesFinal: samples,
        rotatDirecFinal: rotatDirec,
        orientDegreeFinal: orientDegree,
        activityFinal: activity,
        requestData:{}
      }, () => {
        this.getOrgTrack()
      })
    })
  }

  closeModal () {
    this.setState({
      visible: false
    })
    const { closeModal } = this.props
    closeModal()
  }

  getOrgTrack () {
    const { requestData } = this.state
    // 画线图
    const spectrumCharts = [
      {
        chart: this.refs.linex,
        title: 'x轴',
        xtext: '',
        ytext: '',
        series: [
          {
            name: '',
            type: 'line',
            data: requestData.n1 ? requestData.n1.map((d, i) => {
              return [i, Number(d)]
            }) : []
          }
        ]
      },
      {
        chart: this.refs.liney,
        title: 'y轴',
        xtext: '',
        ytext: '',
        series: [
          {
            name: '',
            type: 'line',
            data: requestData.n2 ? requestData.n2.map((d, i) => {
              return [i, Number(d)]
            }) : []
          }
        ]
      }
    ]
    this.lineDraw(spectrumCharts)
    // 画轴心轨迹图
    const { requestType } = this.props
    let url = `${__SPE_API__}api/orgtrack`
    if (requestType === 'wx') {
      url = `${__WXSPE_API__}api/orgtrack`
    }
    fetch(url, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(JSON.stringify(requestData))
    })
    .then(res => res.json())
    .then((json) => {
      this.setState({
        loading: false
      })
      const n1 = json.n1
      const n2 = json.n2
      let max = Math.max(...n1)
      if (max < Math.max(...n2)) {
        max = Math.max(...n2)
      }
      let min = Math.min(...n1)
      if (min > Math.min(...n2)) {
        min = Math.min(...n2)
      }
      this.setState({
        PolarData: json.n1.map((d, i) => {
          return [d, n2[i]]
        }),
        minPolar: Math.floor(min),
        maxPolar: Math.ceil(max)
      }, () => {
        this.draw()
      })
    })
    .catch((error) => {
      console.error(error)
      this.setState({
        loading: false,
        PolarData: []
      }, () => {
        this.draw()
      })
    })
  }

  lineDraw (spectrumCharts: Array<Object>) {
    const component = this
    // 摧毁其他的charts
    // Highcharts.charts.map((d, i) => {
    //   if (d) {
    //     d.destroy()
    //   }
    // })
    function syncExtremes (e) {
      var thisChart = this.chart
      if (e.trigger !== 'syncExtremes') {
        Highcharts.each(Highcharts.charts, function (chart) {
          if (chart && chart !== thisChart) {
            if (chart.xAxis && chart.xAxis[0].setExtremes) {
              chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' })
            }
          }
        })
      }
    }
    Highcharts.setOptions({ global: { useUTC: false } })
    spectrumCharts.map((d, i) => {
      const chart = d.chart
      Highcharts.chart(chart, {
        chart: {
          backgroundColor: 'transparent',
          zoomType: 'x'
        },
        title: {
          text: d.title,
          style: {
            fontSize: 12
          }
        },
        credits:{
          enabled: false
        },
        legend: {
          enabled: false
        },
        tooltip: {
          shared: true,
          crosshairs: true,
          formatter: function () {
            var x = this.x.toFixed(3) * 1000 / 1000
            var value = this.y.toFixed(3) * 1000 / 1000
            return x + '：' + value
          },
          valueDecimals: 2
        },
        xAxis: {
          title: {
            text: d.xtext,
            align: 'high'
          },
          events: {
            setExtremes: syncExtremes
          }
          // categories: this.state.xData
        },
        yAxis: {
          lineWidth: 1,
          tickWidth: 1,
          title: {
            align: 'high',
            offset: 0,
            text: d.ytext,
            rotation: 0,
            y: -15
          }
        },
        plotOptions: {
          line: {
            lineWidth: 1,
            dataGrouping: {
              enabled: false
            }
          },
          series: {
            animation: true,
            allowPointSelect: true,
            cursor: 'pointer',
            point: {
              events: {
                select: function () {
                  // const chart = this.series.chart
                  Highcharts.charts.map((d, i) => {
                    if (d && d.renderTo.title === '实时原始轴心轨迹') {
                      const x = this.category
                      const y = d.series[0].data[x].y
                      const text = x.toFixed(3) * 1000 / 1000 + ': ' +
                      y.toFixed(3) * 1000 / 1000
                      d.xAxis[0].removePlotLine('plot-line-1')
                      d.xAxis[0].addPlotLine({
                        value: this.category,
                        color: '#000',
                        width: 0.5,
                        id: 'plot-line-1'
                      })
                      if (!d.lbl) {
                        d.lbl = d.renderer.label(text, 50, 10)
                          .attr({
                            padding: 5,
                            r: 5,
                            fill: '#f7f7f7',
                            zIndex: 5
                          })
                        .css({
                          color: '#000'
                        })
                          .add()
                      } else {
                        d.lbl.attr({
                          text: text
                        })
                      }
                      // echarts联动
                      let { PolarData } = component.state
                      const PolarData1 = PolarData.map((d, i) => {
                        if (i === 0) {
                          return {symbol: 'circle', name: '起始点', symbolSize: 5, value:d, itemStyle:{normal:{color:'red'}}}
                        } else if (i === x) {
                          return {symbol: 'circle', name: '当前点',symbolSize: 8, value:d, itemStyle:{normal:{color:'#f9bc01'}}}
                        } else {
                          return {value:d}
                        }
                      })
                      component.myChart.setOption({
                        series: [{
                          name:'轴心轨迹',
                          type:'line',
                          symbol: 'none',
                          // symbol: 'circle',
                          // symbolSize: '2',
                          // color: '#0ff',
                          data: PolarData1
                        }]
                      })
                    }
                  })
                }
              }
            }
          }
        },
        series: d.series
      })
    })
  }

  draw () {
    // let PolarData = []
    // for (let i = 0; i <= 360; i = i + 5) {
    //   let r = i
    //   PolarData.push([r, i])
    // }
    this.setState({
      loading: false
    })
    const { PolarData, maxPolar, minPolar } = this.state
    // console.log(JSON.stringify(PolarData));
    const PolarData1 = PolarData.map((d, i) => {
      if (i === 0) {
        return {symbol: 'circle',name: '起始点',symbolSize: 5, value:d, itemStyle:{normal:{color:'red'}}}
      } else {
        return {value:d}
      }
    })
    this.myChart = echarts.init(this.refs.chart)
    let option = {
      color: ['#108ee9', '#2f4554', '#61a0a8'],
      tooltip : {
        trigger: 'axis',
        showDelay : 0,
        axisPointer:{
          show: true,
          type : 'cross',
          lineStyle: {
            type : 'dashed',
            width : 1
          }
        },
        formatter: function (params) {
          let par = params
          if (params.length > 0) {
            par = params[0]
          }
          let name = par.name
          if (name) {
            name = name + '：'
          }
          return name + par.value[0].toFixed(2) + ', ' + par.value[1].toFixed(2)
        }
      },
      xAxis : [
        {
          // type : 'value',
          // scale:true,
          max: maxPolar,
          min: minPolar
        }
      ],
      yAxis : [
        {
          // type : 'value',
          // scale:true,
          max: maxPolar,
          min: minPolar
          // axisTick: { length:5 }
        }
      ],
      plotOptions: {
        line: {
          lineWidth: 1,
          dataGrouping: {
            enabled: false
          }
        },
        series: {
          animation: true
        }
      },
      series : [
        {
          name:'轴心',
          symbol: 'none',
          type:'line',
          data: PolarData1
        }
      ]
    }
    // let option = {
    //   color: ['#108ee9', '#2f4554', '#61a0a8'],
    //   // title: {
    //   //   text: '极坐标双数值轴'
    //   // },
    //   // legend: {
    //   //   data: ['line']
    //   // },
    //   polar: {
    //     center: ['50%', '54%']
    //   },
    //   tooltip: {
    //     trigger: 'axis',
    //     axisPointer: {
    //       type: 'cross'
    //     }
    //   },
    //   angleAxis: {
    //     type: 'value',
    //     startAngle: 0
    //   },
    //   radiusAxis: {
    //     min: 0
    //   },
    //   series: [{
    //     coordinateSystem: 'polar',
    //     name: '',
    //     type: 'line',
    //     showSymbol: false,
    //     symbolSize: 4,
    //     data: PolarData
    //   }],
    //   animationDuration: 2000
    // }
    this.myChart.setOption(option)
    window.onresize = this.myChart.resize
  }
  render () {
    const { loading, infoData, plainOptions, channelValue, samplesFinal, rotatDirecFinal, orientDegreeFinal } = this.state
    const { checkTime, requestType } = this.props

    const radioStyle = {
      display: 'block',
      paddingLeft: '10px'
    }
    let rotatDirecLabel = '' // 旋转角度
    if (rotatDirecFinal === '0') {
      rotatDirecLabel = '顺时针'
    } else if (rotatDirecFinal === '1') {
      rotatDirecLabel = '逆时针'
    }
    // 测点通道展示
    const { channelData, bearingNameFinal } = this.state
    let channelNames = []
    if (channelData.length > 0) {
      channelNames = channelData[0].channelIds.filter((dd) => dd.bearingName === bearingNameFinal)
    }

    // 速度计算方式
    const { activityFinal } = this.state
    let activityName = ''
    if (activityFinal === '0') {
      activityName = '有效'
    } else if (activityFinal === '1') {
      activityName = '无效'
    } else if (activityFinal === '2') {
      activityName = '无键'
    } else if (activityFinal === '3') {
      activityName = '模拟'
    } else if (activityFinal === '4') {
      activityName = '无键计算转速'
    }
    const bool = requestType === 'wx' ? true : false
    return (
      <div className={styles['main']}>
        <Row className={styles['mainCon']}>
          <Popover content={
            <div>
              <div className={styles['conditionTop']}>
                <RadioGroup onChange={this.channelChange} value={channelValue}>
                  {
                    plainOptions.map((d, i) => {
                      return <Radio style={radioStyle} key={i} title={d.label} value={d.value}>{d.label}</Radio>
                    })
                  }
                </RadioGroup>
              </div>
              <p className={styles['leftFooter']}>
                <Button type='primary' onClick={this.refer} disabled={loading}>绘制</Button>
                <Button style={{ marginLeft: '10px' }} onClick={this.kmxDraw} disabled={loading}>KMX取值</Button>
              </p>
            </div>
          } trigger='click' title='通道：'>
            <Button type='primary' className={styles['conditionBtn']}>选择测点</Button>
          </Popover>
          <Col span={5}>
            基本信息：
            <div className={styles['leftCon']}>
              <div className={styles['infoCon']}>
                <label key='a'> <span>当前时间:</span> <b>{moment(checkTime).format('YYYY-MM-DD HH:mm:ss')}</b></label>
                <label key='aa'> <span>测点:</span> <b>{bearingNameFinal}</b></label>
                <label key='aaa'> <span>通道:</span> <b>{
                  channelNames.map((d, i) => {
                    let label = d.name
                    if (i === 1) {
                      label = '/' + d.name
                    }
                    return label
                  })
                }</b></label>
                <label key='bb'> <span>采样点数:</span> <b>{samplesFinal}</b></label>
                <label key='bbb'> <span>旋转方向:</span> <b>{rotatDirecLabel}</b></label>
                <label key='ba'> <span>安装角度:</span> <b>{orientDegreeFinal}{
                   orientDegreeFinal ? '°' : ''
                }</b></label>
                <label key='bc'> <span>转速计算:</span> <b>{activityName}</b></label>
                {
                  infoData.length > 0 ? infoData.map((d, i) => {
                    return <label key={i}> <span>{d.name}:</span> <b>{d.value.toFixed(3) * 1000 / 1000}</b></label>
                  }) : false
                  // <p className={styles['infoNo']}>暂无信息，请选择测点</p>
                }
              </div>
            </div>
          </Col>
          <Col span={19}>
            <Spin spinning={loading} tip='加载中...'>
              <img src='/ni.png'
                style={{ position:'absolute', top:'60px', left: '40px', fontSize: '26px', display: rotatDirecFinal === '1' ? 'inline-block' : 'none' }} />
              <img src='/shun.png'
              style={{ position:'absolute', top:'60px', left: bool ? '195px' : '285px', fontSize: '26px', display: rotatDirecFinal === '0' ? 'inline-block' : 'none' }} />
              <div ref='chart' style={{ width: bool ? 300 : 400, height: bool ? 300 : 400 }} className={styles['chart']} />
              <div className={styles['chartR']} >
                <div ref='linex' title='实时原始轴心轨迹' className={styles['chartLine']} />
                <div ref='liney' title='实时原始轴心轨迹' className={styles['chartLine']} />
              </div>
            </Spin>
          </Col>
        </Row>
      </div>
    )
  }
}

export default HistoryPolar
